package com.leon.registerclient;

import java.util.HashMap;
import java.util.Map;

public class ClientCachedServiceRegistry {

    /**
     * 服务注册表拉取的间隔时间
     */
    private static final long FETCH_INTERVAL = 30 * 1000L;

    private Map<String, Map<String, ServiceInstance>> registry = new HashMap<>();

    private Daemon daemon;

    private RegisterClient registerClient;

    private HttpSender httpSender;

    public ClientCachedServiceRegistry(RegisterClient registerClient, HttpSender httpSender) {
        this.daemon = new Daemon();
        this.registerClient = registerClient;
        this.httpSender = httpSender;
    }

    /**
     * 初始化
     */
    public void initialize() {
        this.daemon.start();
    }

    /**
     * 销毁这个组件
     */
    public void destroy() {
        this.daemon.interrupt();
    }

    /**
     * 负责定时拉取注册表到缓存
     */
    private class Daemon extends Thread {

        @Override
        public void run() {
            while (true) {
                while (registerClient.isRunning()) {
                    try {
                        registry = httpSender.fetchServiceRegistry();
                        Thread.sleep(FETCH_INTERVAL);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public Map<String, Map<String, ServiceInstance>> getRegistry() {
        return registry;
    }
}
